"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ClientManager = void 0;
const debug_1 = __importDefault(require("debug"));
const events_1 = require("events");
const Client_1 = require("./Client");
const TunnelAgent_1 = require("./TunnelAgent");
const id_generator_1 = require("../utils/id-generator");
const net = __importStar(require("net"));
// Manage sets of clients
//
// A client is a "user session" established to service a remote localtunnel client
class ClientManager extends events_1.EventEmitter {
    constructor(opt = {}) {
        super();
        this.opt = opt;
        this.clients = new Map();
        this._stats = {
            tunnels: 0
        };
        this.debug = (0, debug_1.default)('lt:ClientManager');
        // 创建共享的 TCP 服务器
        this.sharedServer = net.createServer();
        this.initSharedServer();
    }
    initSharedServer() {
        const port = this.opt.tunnel_port || 7002;
        this.sharedServer.listen(port, '0.0.0.0', () => {
            this.debug(`共享 TCP 服务器监听在端口 ${port}`);
        });
        this.sharedServer.on('connection', (socket) => {
            // 这里我们需要识别这个连接属于哪个客户端
            // 可以通过初始握手消息来实现
            this.handleNewConnection(socket);
        });
    }
    handleNewConnection(socket) {
        let buffer = '';
        let registered = false;
        const cleanup = () => {
            socket.removeAllListeners('data');
            socket.removeAllListeners('timeout');
            socket.removeAllListeners('error');
        };
        socket.on('data', (data) => {
            if (registered) {
                return; // 已经注册过的连接不再处理注册消息
            }
            buffer += data.toString();
            if (buffer.includes('\n')) { // 使用换行符来判断消息完整性
                try {
                    const message = JSON.parse(buffer);
                    const clientId = message.clientId;
                    if (message.type === 'register' && clientId) {
                        const client = this.clients.get(clientId);
                        if (client) {
                            registered = true;
                            cleanup();
                            // 发送确认消息
                            socket.write(JSON.stringify({
                                type: 'registered',
                                success: true
                            }) + '\n');
                            // 将socket交给对应的客户端处理
                            client.handleSocket(socket);
                            this.debug(`Client ${clientId} registered successfully`);
                        }
                        else {
                            this.debug(`Unknown client ${clientId} tried to register`);
                            socket.destroy();
                        }
                    }
                    else {
                        this.debug('Invalid registration message');
                        socket.destroy();
                    }
                }
                catch (err) {
                    this.debug('Failed to parse registration message:', err);
                    socket.destroy();
                }
                buffer = '';
            }
        });
        // 设置更长的超时时间
        socket.setTimeout(10000);
        socket.on('timeout', () => {
            this.debug('Connection timed out during registration');
            socket.destroy();
        });
        socket.on('error', (err) => {
            this.debug('Socket error during registration:', err);
            socket.destroy();
        });
    }
    // create a new tunnel with `id`
    // if the id is already used, a random id is assigned
    // if the tunnel could not be created, throws an error
    async newClient(id) {
        const clients = this.clients;
        const stats = this._stats;
        // can't ask for id already is use
        if (clients.has(id)) {
            id = (0, id_generator_1.generateReadableId)();
        }
        const maxSockets = this.opt.max_tcp_sockets;
        const tunnelPort = this.opt.tunnel_port;
        const agent = new TunnelAgent_1.TunnelAgent({
            clientId: id,
            maxTcpSockets: maxSockets,
            tunnelPort: tunnelPort
        });
        const client = new Client_1.Client({
            id,
            agent,
        });
        // add to clients map immediately
        // avoiding races with other clients requesting same id
        clients.set(id, client);
        client.once('close', () => {
            this.removeClient(id);
        });
        // try/catch used here to remove client id
        try {
            const info = await agent.listen();
            ++stats.tunnels;
            this.emit('client:connect', id);
            return {
                id: id,
                port: info.port,
                max_conn_count: maxSockets || 10,
            };
        }
        catch (err) {
            this.removeClient(id);
            // rethrow error for upstream to handle
            throw err;
        }
    }
    removeClient(id) {
        this.debug('removing client: %s', id);
        const client = this.clients.get(id);
        if (!client) {
            return;
        }
        --this._stats.tunnels;
        this.clients.delete(id);
        client.close();
        this.emit('client:disconnect', id);
    }
    hasClient(id) {
        return this.clients.has(id);
    }
    getClient(id) {
        return this.clients.get(id);
    }
    getStats() {
        return this._stats;
    }
}
exports.ClientManager = ClientManager;
